package com.lijie.userservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lijie.basecommon.exception.BusinessException;
import com.lijie.userservice.entity.TbUser;
import com.lijie.userservice.service.TbUserService;
import com.lijie.userservice.vo.TbUserVO;
import com.lijie.userservice.vo.LoginVo;
import com.lijie.utilscommon.pwdmd5.MD5Utils;
import com.lijie.utilscommon.response.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author ange
 * @since 2020-07-19
 */
@Api(value = "用户管理")
@RestController
@RequestMapping("/userservice/tb-user")
@CrossOrigin
public class TbUserController {
    @Autowired
    private TbUserService tbUserService;

    /**
     * 查询所有用户
     *
     * @return
     */
    @ApiOperation(value = "查询所有用户")
    @GetMapping("/users")
    public Result user() {
       
        List<TbUser> users = tbUserService.list();

        return Result.ok().data("users", users);
    }

    @ApiOperation(value = "逻辑删除用户")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer id) {

        boolean b = tbUserService.removeById(id);
        if (b) {
            return Result.ok();
        } else {
            return Result.error();
        }

    }

    @ApiOperation(value = "分页查询")
    @GetMapping("/{current}/{size}")
    public Result userPage(@PathVariable("current") Integer current, @PathVariable("size") Integer size) {
        Page<TbUser> page = new Page<>(current, size);
        Page<TbUser> userPage = tbUserService.page(page);
        Long total = userPage.getTotal();
        List<TbUser> records = userPage.getRecords();
        return Result.ok().data("total", total).data("records", records);
    }

    @ApiOperation(value = "根据条件分页查询")
    @GetMapping("/userPageBycon/{current}/{size}")
    public Result userpageBYCondition(@PathVariable("current") Integer current, @PathVariable("size") Integer size, TbUserVO tbUserVO){
        Page<TbUser> page = new Page<>(current, size);
        QueryWrapper<TbUser> queryWrapper=new QueryWrapper<>();
        if(!StringUtils.isEmpty(tbUserVO.getUsername())){
            queryWrapper.like("username",tbUserVO.getUsername());
        }

        if(!StringUtils.isEmpty(tbUserVO.getEmail())){
            queryWrapper.like("email",tbUserVO.getEmail());
        }
        if(!StringUtils.isEmpty(tbUserVO.getSex())){
            queryWrapper.eq("sex",tbUserVO.getSex());
        }
        if(!StringUtils.isEmpty(tbUserVO.getDepartmentId())){
            queryWrapper.eq("department_id",tbUserVO.getDepartmentId());
        }
        if(!StringUtils.isEmpty(tbUserVO.getNickname())){
            queryWrapper.like("nickname",tbUserVO.getNickname());
        }
        Page<TbUser> userPage = tbUserService.page(page,queryWrapper);
        Long total = userPage.getTotal();
        List<TbUser> records = userPage.getRecords();
        return Result.ok().data("total", total).data("records", records);

    }


    @PostMapping("/login")
    @ApiOperation(value = "登录方法")
    public Result login(@RequestBody LoginVo loginVo){
        QueryWrapper<TbUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",loginVo.getUsername()).eq("password",loginVo.getPassword());
        TbUser tbUser = tbUserService.getOne(queryWrapper);
        if (tbUser != null){
            return Result.ok().data("tbUser",tbUser);
        }
        return Result.error().message("此用户不存在");
    }

    @ApiOperation(value = "增加用户")
    @PostMapping("/addUser")
    public Result addUser(@RequestBody TbUser tbUser){
        tbUser.setStatus(1);
        tbUser.setSalt(UUID.randomUUID().toString().substring(0,32));
        tbUser.setType(1);
        tbUser.setPassword("123456");
        tbUser.setPassword(MD5Utils.md5Encryption(tbUser.getPassword(),tbUser.getSalt()));
        tbUser.setAvatar("http://thirdqq.qlogo.cn/g?b=oidb&k=icTYjyV5afABvE1v4ge9SLg&s=100&t=1584195695");
        boolean save = tbUserService.save(tbUser);
        if(save){
            return Result.ok();
        }else {
            return  Result.error();
        }
    }


    @ApiOperation("根据id查询用户")
    @GetMapping("/findById/{id}")
    public Result findById(@PathVariable("id") Long id){
        TbUser byId = tbUserService.getById(id);
        if(StringUtils.isEmpty(byId)){
            //用户不存在
            throw new BusinessException(20001,"用户不存在");
        }
        return Result.ok().data("byId",byId);
    }

    @ApiOperation("根据id修改用户")
    @PutMapping("/updById")
    public Result updById(@RequestBody(required = false) TbUser tbUser){
        tbUser.setCreateTime(tbUser.getCreateTime());
        tbUser.setModifiedTime(new Date());
        boolean b = tbUserService.updateById(tbUser);
        return Result.ok().data("b",b);
    }


    @ApiOperation(value = "根据条件分页查询用户信息和部门信息")
    @PostMapping("/userAndDeptBycon/{current}/{size}")
    public Result userAndDeptBycon(@PathVariable("current") Integer current, @PathVariable("size") Integer size,@RequestBody(required = false) TbUserVO tbUserVO){
        Page<TbUser> page=new Page<>(current,size);
        QueryWrapper<TbUser> queryWrapper=getWrapper(tbUserVO);
        return  Result.ok().data("total",tbUserService.findUserAndDeptCount()).data("record",tbUserService.findUserAndDept(current,size));
    }

    public QueryWrapper<TbUser> getWrapper(TbUserVO tbUserVO){
        QueryWrapper<TbUser> queryWrapper=new QueryWrapper<>();
        if(!StringUtils.isEmpty(tbUserVO.getUsername())){
            queryWrapper.like("username",tbUserVO.getUsername());
        }

        if(!StringUtils.isEmpty(tbUserVO.getEmail())){
            queryWrapper.like("email",tbUserVO.getEmail());
        }
        if(!StringUtils.isEmpty(tbUserVO.getSex())){
            queryWrapper.eq("sex",tbUserVO.getSex());
        }
        if(!StringUtils.isEmpty(tbUserVO.getDepartmentId())){
            queryWrapper.eq("department_id",tbUserVO.getDepartmentId());
        }
        if(!StringUtils.isEmpty(tbUserVO.getNickname())){
            queryWrapper.like("nickname",tbUserVO.getNickname());
        }
        return queryWrapper;
    }


    @ApiOperation(value = "使用mp查询用户信息和部门信息")
    @PostMapping("/findUserPage/{current}/{size}")
    public Result findUserPage(@PathVariable("current") Integer current, @PathVariable("size") Integer size,@RequestBody(required = false) TbUserVO tbUserVO){
        Page<TbUser> page=new Page<>(current,size);
        QueryWrapper<TbUser> queryWrapper=getWrapper(tbUserVO);
        IPage<TbUser> userPage = tbUserService.findUserPage(page, queryWrapper);
        return Result.ok().data("total",userPage.getTotal()).data("records",userPage.getRecords());
    }

    /**
     * 导出
     */
    @ApiOperation(value = "导出用户信息")
    @PostMapping(value = "/export")
    /*@RequestMapping(value = "/export", method = RequestMethod.POST)*/
    public void exportStudentInfoExcel(HttpServletResponse response,@RequestBody(required = false) TbUserVO tbUserVO) throws IOException {
        QueryWrapper<TbUser> queryWrapper=getWrapper(tbUserVO);
        List<TbUser> tbUsers = tbUserService.list(queryWrapper);
        tbUserService.exportUserInfoExcel(response,tbUsers);
    }

    @ApiOperation(value = "导入用户信息")
    @RequestMapping(value = "/import",method = {RequestMethod.POST})
    public String importStudentInfoExcel(@RequestParam("file") MultipartFile file) throws IOException{
        tbUserService.importUserInfoExcel(file);
        return "success";
    }
    /**
     * 改变用户状态
     * @param id
     * @param status
     * @return
     */
    @ApiOperation (value = "修改用户状态",notes = "修改用户状态")
    @PutMapping("/updStatus")
    public Result updStatus(Integer id,Integer status){
        if (tbUserService.updStatus (id,status)){
            return Result.ok ();
        }else{
            return Result.error ().message ("改变用户状态失败");
        }
    }



}



